package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"recruit-ease/cache"
	"recruit-ease/model"
	"strconv"
	"time"
)

func ListRecruit(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "2"))
	offset := (page - 1) * size
	var list []model.Recruit
	redis_key := "list" + strconv.Itoa(page)
	chchaData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if chchaData == "" {
		model.DB.Offset(offset).Limit(size).Order("Created_At DESC").Find(&list)
		jsData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_key, jsData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(chchaData), &list)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "获取成功",
		"data": list,
	})
	return
}

func DetailRecruit(c *gin.Context) {
	id := c.Query("id")
	var recruit model.Recruit
	model.DB.Where("id=?", id).Find(&recruit)
	redis_key := "detail_" + id
	jsonData, _ := json.Marshal(recruit)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "获取成功",
		"data": recruit,
	})
	return
}

func LikeCreate(c *gin.Context) {
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	uid, _ := strconv.Atoi(c.PostForm("uid"))
	data := model.LikeRecruit{
		UserID:    uid,
		RecruitID: rid,
	}
	err := model.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func LikeRecruit(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "2"))
	offset := (page - 1) * size
	var list []model.LikeRecruit
	redis_key := "like" + strconv.Itoa(page)
	chchaData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if chchaData == "" {
		model.DB.Offset(offset).Limit(size).Order("Created_At DESC").Find(&list)
		jsData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_key, jsData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(chchaData), &list)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "获取成功",
		"data": list,
	})
	return
}
